﻿using System.Collections.Generic;
using System.Drawing;
using System.Dynamic;
using Newtonsoft.Json;

namespace Maple.Weixin.MP.Entities
{
    public class TemplateMessageData
    {
        private readonly string value;
        private readonly string color;

        public TemplateMessageData(string value, string color) {
            this.value = value;
            this.color = color;
        }

        public TemplateMessageData(string value, Color color) :
            this(value, ColorTranslator.ToHtml(color)) {}

        public string Value { get { return value; } }
        public string Color { get { return color; } }
    }

    public class TemplateMessage
    {
        private readonly string openid;
        private readonly string templateid;
        private readonly string linkUrl;
        private readonly string topColor;
        private readonly IDictionary<string, TemplateMessageData> data;

        public TemplateMessage(string openid, string templateid, string linkUrl, string topColor,
                                   IDictionary<string, TemplateMessageData> data) {
            this.openid = openid;
            this.templateid = templateid;
            this.linkUrl = linkUrl;
            this.topColor = topColor;
            this.data = data;
        }

        public string ToJson() {
            dynamic dataObj = new ExpandoObject();
            foreach (var dataKey in data.Keys) {
                ((IDictionary<string, object>) dataObj).Add(dataKey,
                    new
                        {
                            value = data[dataKey].Value,
                            color = data[dataKey].Color
                        });
            }
            var entity = new
                {
                    touser = openid,
                    template_id = templateid,
                    url = linkUrl,
                    topcolor = topColor,
                    data = dataObj
                };
            return JsonConvert.SerializeObject(entity);
        }
    }
}
